import os

from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flasgger import Swagger
# from config import Config
from dotenv import load_dotenv
import redis

# 加载 .env 文件中的环境变量
load_dotenv()

app = Flask(__name__,
            template_folder='../templates',
            static_folder='../static',  # 设置静态资源的 URL
            static_url_path='/')
CORS(app)  # 添加这一行来启用 CORS
# 初始化 Flasgger
swagger = Swagger(app)

# app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+mysqldb://{Config.MYSQL_USER}:{Config.MYSQL_PWD}@{Config.MYSQL_HOST}:{Config.MYSQL_PORT}/{Config.MYSQL_DB}'

# 组装数据库连接字符串
app.config['SQLALCHEMY_DATABASE_URI'] = (
    f"mysql+pymysql://{os.getenv('MYSQL_USER')}:{os.getenv('MYSQL_PWD')}"
    f"@{os.getenv('MYSQL_HOST')}:{os.getenv('MYSQL_PORT')}/{os.getenv('MYSQL_DB')}"
)
# 增加连接超时和重试机制
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    "pool_recycle": 1800,  # 30 分钟回收一次连接
    'pool_pre_ping': True,  # 连接前检查有效性
    'pool_size': 10,  # 连接池大小
    'max_overflow': 20,  # 超出pool_size后最多可创建的连接数
    "connect_args": {
        "connect_timeout": 10,  # 连接超时时间 - 10秒
        "read_timeout": 30,     # 读取超时时间 - 30秒
        "write_timeout": 60,    # 写入超时时间 - 60秒
    }
}

# Redis 配置
app.config['REDIS_URL'] = os.getenv('REDIS_URL', 'redis://localhost:6379/1')


# 设置密钥
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')



db = SQLAlchemy(app)
login_manager = LoginManager(app)

# 初始化 Redis
from utils.redis import redis_client_instance
redis_client_instance.init_app(app)

# 路由管理
from routes import homepage_router
from routes import user_route
from routes import vep_route
from routes import gep_route
from routes import gep_routesTest